import subprocess
import os
from datetime import datetime


log_dir = "logs"
os.makedirs(log_dir, exist_ok=True)


current_date = datetime.now().strftime("%Y-%m-%d")


log_file1 = os.path.join(log_dir, f"GrabImage1_{current_date}.log")
log_file2 = os.path.join(log_dir, f"GrabImage2_{current_date}.log")

# 使用 taskset 分别将两个子进程绑定到不同的 CPU 核
cpu1 = "3"  # 将 GrabImage1 绑定到 CPU 核 0
cpu2 = "4"  # 将 GrabImage2 绑定到 CPU 核 1

with open(log_file1, "w") as log1, open(log_file2, "w") as log2:
    # proc1 = subprocess.Popen(["python3", "GrabImage1.py"], stdout=log1, stderr=log1)
    # proc2 = subprocess.Popen(["python3", "GrabImage2.py"], stdout=log2, stderr=log2)
    # 启动两个子进程并绑定到不同的 CPU 核
    proc1 = subprocess.Popen(["taskset", "-c", cpu1, "python3", "GrabImage1.py"], stdout=log1, stderr=log1)
    proc2 = subprocess.Popen(["taskset", "-c", cpu2, "python3", "GrabImage2.py"], stdout=log2, stderr=log2)

    try:
        # 等待两个子进程完成（通过手动终止）
        proc1.wait()
        proc2.wait()
    except KeyboardInterrupt:
        # 捕获 Ctrl+C，终止子进程
        print("Terminating processes...")
        proc1.terminate()
        proc2.terminate()
